<template>
  <div class="drugStorage">
    <div class="drugStorage-page">
      <div class="drugStorage-page-content">
        <div class="drugStorage-page-form">
          <el-input
            v-model="storageName"
            style="width: 300px"
            placeholder="药库名称"
            @blur="handlePageChange(1)" 
            @change="handlePageChange(1)"
            :suffix-icon="Search"
          />
          <div class="drugStorage-page-form-right">
            <el-button type="primary" @click="drugStrorageAdd" v-btnPermission="'btn-storage-updata'"
              ><el-icon style="margin-right: 5px">
                <Plus /> </el-icon
              >新增</el-button
            >
          </div>
        </div>
        <div class="drugStorage-page-table">
          <Table
            :columns="tableColumns"
            @selectionChange="selectionChange"
            :loading="loading"
            :data-source="tableData"
          />
        </div>
        <div class="drugStorage-page-pagination">
          <Pagination
            style="margin-left: auto"
            :key="pageSize + 'Pagination' + currentPage"
            :count="total"
            :page-size="pageSize"
            :pageNo="currentPage"
            @onPagechange="handlePageChange"
            @onSizechange="handleSizeChange"
          />
        </div>
      </div>
    </div>
    <Dialog
      :width="500"
      :title="title"
      :radius="12"
      :visible="visible"
      @close="visible = false"
      ref="dialogRef"
    >
      <div class="drugStorage-dialog">
        <el-form :model="form" :rules="rules" label-width="100px" label-position="left" ref="formRef">
          <el-form-item label="药库名称" prop="storageName">
            <el-input
              v-model="form.storageName"
              placeholder="请输入药库名称" 
            ></el-input>
          </el-form-item>
          <el-form-item label="管理员" prop="managerId">
            
            <el-select
              v-model="form.managerId" filterable
              placeholder="请选择管理员" clearable
            >
               <el-option v-for="item in EmployeeList" :key="item.empId" :label="item.empName"
                            :value="item.empId" />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button type="primary" plain @click="close">取消</el-button>
        <el-button
          type="primary"
          @click="drugStrorageUpdata"
          :loading="updataLoading"
          >确定</el-button
        >
      </template>
    </Dialog>
  </div>
</template>

<script setup lang="ts">
import { Search, Plus } from '@element-plus/icons-vue';
import { ElForm } from 'element-plus';
import type { TableColumn } from '@/types/table';
import type { FormStorage, List } from '@/types/storage/index';
import type { FormInstance, FormRules, Action } from 'element-plus';
import {getEmployeeList} from '@/api/clinic';

import {
  getStorageList,
  addStorage,
  updateStorage,
  deleteStorage,
  enableStorage,
  disableStorage,
  setDefault,
} from '@/api/storage';
const loading = ref<boolean>(false);
const updataLoading = ref<boolean>(false);
const formRef = ref<FormInstance>();
const visible = ref<boolean>(false);
const tableColumns: TableColumn[] = [
  { prop: 'storageName', label: '药库名称' },
  { prop: 'empName', label: '管理员' },
  { prop: 'empNo', label: '管理员工号' },
  { prop: 'isDefault', label: '是否默认' },
  { prop: 'isEnabled', label: '启用状态', type: 'tag' },
  { prop: 'createBy', label: '创建人' },
  { prop: 'createTime', label: '创建时间' },
  // { prop: 'updateTime', label: '具体内容' },
  {
    prop: 'action',
    label: '操作',
    type: 'action',
    width: 250,
    componentProps: {
      fixed: 'right',
    },
    buttonGroup: [
      {
        label: '编辑',
        type: 'text',
        permissions: 'btn-storage-edit',
        click: (row: any) => {
          //console.log('编辑', row);
          title.value = '编辑药库';
          form.value.storageName = row.storageName;
          form.value.storageId = row.storageId;
          form.value.managerId = row.managerId || 0; // 新增字段
          // 打开弹窗
          visible.value = true;
        },
      },
      {
        label: '启用',
        statusName: ['isEnabled'],
        permissions: 'btn-storage-enable',
        status: '停用',
        type: 'text',
        click: (row: any) => {
          enableStorage(row.storageId).then((res) => {
            if (res.code == '200') {
              getStorageLists(); // 刷新列表

              ElMessage({
                type: 'success',
                message: '操作成功',
              });
            } else {
              // ElMessage({
              //   type: 'warning',
              //   message: res.msg,
              // });
            }
          });
        },
      },
      {
        label: '停用',
        statusName: ['isEnabled'],
        permissions: 'btn-storage-disable',
        status: '启用',
        type: 'text',
        color: '#D90000',
        click: (row: any) => {
          disableStorage(row.storageId).then((res) => {
            if (res.code == '200') {
              getStorageLists(); // 刷新列表

              ElMessage({
                type: 'success',
                message: '操作成功',
              });
            } else {
              // ElMessage({
              //   type: 'warning',
              //   message: res.msg,
              // });
            }
          });
        },
      },
      {
        label: '删除',
        type: 'text',
        permissions: 'btn-storage-del',

        color: '#D90000',
        click: (row: any) => {
          ElMessageBox.alert('确定要删除吗？', '删除药库', {
            // if you want to disable its autofocus
            // autofocus: false,
            confirmButtonText: '确定',
            callback: (action: Action) => {
               if(action == 'cancel'){
                  return;
              }
              try {
                deleteStorage(row.storageId).then((res) => {
                  if (res.code == '200') {
                    getStorageLists(); // 刷新列表

                    ElMessage({
                      type: 'success',
                      message: '操作成功',
                    });
                  } else {
                    // ElMessage({
                    //   type: 'warning',
                    //   message: res.msg,
                    // });
                  }
                });
              } catch (error: any) {
                //console.log(error, '删除失败');
              }
            },
          });
        },
      },
      {
        label: '设为默认',
        type: 'text',
        permissions: 'btn-storage-Default',
        statusName: ['isDefault'],
        status: '否',
        click: (row: any) => {
          setDefault(row.storageId).then((res) => {
            if (res.code == '200') {
              getStorageLists(); // 刷新列表

              ElMessage({
                type: 'success',
                message: '操作成功',
              });
            } else {
              // ElMessage({
              //   type: 'warning',
              //   message: res.msg,
              // });
            }
          });
        },
      },
    ],
  },
];

const EmployeeList = ref<any[]>([]);
const getEmployeeListApi = async ()=> {
  const data = {
    deptName:'',
    pageNo: 1,
    pageSize: 9999,
  };
  const res = await getEmployeeList(data);
   if(res.code != '200'){
            //ElMessage.error(res.msg);
            return
        }
  EmployeeList.value = res.data.list;
}
getEmployeeListApi()


const userinfo = getUserInfo(); // 获取用户信息
//表单
const storageName = ref<string>('');
var form = ref<FormStorage>({
  storageName: '',
  managerId:  '', // 新增字段
});

const rules: FormRules = {
  storageName: [{ required: true, message: '请输入药库名称', trigger: 'blur' }],
  managerId: [{ required: true, message: '请选择管理员', trigger: 'blur' }],
};

const drugStrorageUpdata = async (): Promise<void> => {
  if (!formRef.value) return;
  // 这里可以添加表单验证逻辑
  formRef.value.validate((valid: boolean) => {
    if (valid) {
      //console.log('表单验证通过');
      if (form.value.storageId) {
        updataLoading.value = true; // 开始加载
        // 编辑逻辑
        updateStorage(form.value).then((res) => {
          updataLoading.value = false; // 停止加载
          // 关闭弹窗
          if (res.code == '200') {
            form.value = {
              storageName: '',
              managerId:'', // 新增字段
            }; 
            getStorageLists(); // 刷新列表
            close();
            ElMessage({
              type: 'success',
              message: '操作成功',
            });
          } else {
            // ElMessage({
            //   type: 'warning',
            //   message: res.msg,
            // });
          }
        });
      } else {
        // 新增逻辑
        addStorage(form.value).then((res) => {
          updataLoading.value = false; // 停止加载
          if (res.code == '200') {
            form.value = {
              storageName: '',
              managerId:'', // 新增字段
            }; 
            // 重置表单
            close();

            getStorageLists(); // 刷新列表
            ElMessage({
              type: 'success',
              message: '操作成功',
            });
          } else {
            // ElMessage({
            //   type: 'warning',
            //   message: res.msg,
            // });
          }
        });
      }
     
    } else {
      //console.error('表单验证失败');
      return;
    }
  });
  // await formRef.value.validate();
};

const title = ref<string>('');
const drugStrorageAdd = () => {
  title.value = '新增药库';
  form.value = {
    storageName: '',
    managerId: '',
  }; // 重置表单
  visible.value = true;

  //console.log(visible.value, 'visible.value');
};

const selectionChange = (val: any) => {
  //console.log('选中数据:', val);
};

const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 获取药库列表
const tableData = ref<List[]>([]);
const getStorageLists = async () => {
  loading.value = true;
  try {
    const res = await getStorageList({
      storageName: storageName.value,
      pageNo: currentPage.value,
      pageSize: pageSize.value,
    });
     if(res.code != '200'){
            //ElMessage.error(res.msg);
            return
        }
    res.data.list.forEach((item: any) => {
      item.isEnabled = item.isEnabled === '1' ? '启用' : '停用';
    });
    res.data.list.forEach((item: any) => {
      item.isDefault = item.isDefault === '1' ? '是' : '否';
    });

    tableData.value = res.data.list || [];
    // 更新总条数
    total.value = res.data.totalCount || 0;
  } catch (error) {
    //console.error('请求错误:', error);
  } finally {
    loading.value = false;
  }
};
getStorageLists();

const close = () => {
  //console.log('关闭弹窗');
  // 重置表单
  form.value = {
    storageName: '',
    managerId:'',
  };
  visible.value = false; // 关闭弹窗
};

const handlePageChange = (page: number) => {
  //console.log('当前页:', page);
  currentPage.value = page;
  getStorageLists(); // 重新获取数据
};
const handleSizeChange = (size: number) => {
  //console.log('每页条数:', size);
  pageSize.value = size;
  currentPage.value = 1; // 重置当前页为1
  getStorageLists(); // 重新获取数据
};
</script>

<style lang="scss" scoped>
.drugStorage {
  height: 100%;
}

.drugStorage-dialog-footer {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
}

.drugStorage-dialog {
  width: 100%;
  margin: 0 auto;
}

.drugStorage-page {
  background: #fff;
  border-radius: 6px;
  height: 100%;

  .drugStorage-page-nav {
    display: flex;
    align-items: center;
    justify-content: left;
    border-radius: 4px;
    border-bottom: 1px solid #e7e7e7;

    .el-dropdown-link {
      background: rgba(22, 173, 164, 0.08);
      border-radius: 0px 0px 0px 0px;
      padding: 16px 21px;
      cursor: pointer;
      color: var(--el-color-primary) !important;
      display: flex;
      font-size: 16px;
      align-items: center;
    }
  }

  .drugStorage-page-content {
    padding: 10px 24px;
    height: calc(100% - 65px);

    .drugStorage-page-form {
      display: flex;
      align-items: center;

      .drugStorage-page-form-right {
        margin-left: auto;
      }
    }

    .drugStorage-page-table {
      margin-top: 22px;
      height: calc(100% - 68px);
    }

    .drugStorage-page-pagination {
      margin-top: 24px;
      display: flex;
      align-items: center;
    }
  }
}
</style>
